package br.com.portalaberto.telas;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import br.com.portalaberto.core.UIController;

public class Imagem extends Canvas{
	
	public static int width;
	public static int height;
	
	private Command sair;
	private Command ok;

	private UIController controlador;
	private Image img;

	private static Imagem instance;
	
	public static Imagem getInstance(UIController controlador){
		if (instance == null){
			instance = new Imagem(controlador, null);
		}
		return instance;
	}
	
	public static Imagem getInstance(UIController controlador, Image im){
		if (instance == null){
			instance = new Imagem(controlador, im);
		}
		return instance;
	}

	private Imagem(UIController controlador, Image im){
		this.controlador = controlador;
		this.img = im;
        width = getWidth();
        height = getHeight();
		sair = new Command("Voltar", Command.EXIT, 0);
		ok = new Command("OK", Command.OK, 1);
		this.addCommand(sair);
		this.addCommand(ok);
		this.setCommandListener(controlador);
		repaint();
	}
	
	private void limpaTela(Graphics graphics) {
		graphics.setColor(0x708090);
		graphics.fillRect(0, 0, width, height);
		graphics.setColor(0x708090);
	}
	
	protected void paint(Graphics g) {
		limpaTela(g);
		g.drawImage(resizeImage(img), 0, 0, Graphics.TOP | Graphics.LEFT);
	}
	
	public Command getSair() {
		return sair;
	}

	public Command getOk() {
		return ok;
	}
	
	public Image getImg() {
		return img;
	}
	
	private Image resizeImage(Image src) {
	      int srcWidth = src.getWidth();
	      int srcHeight = src.getHeight();
	      Image tmp = Image.createImage(width, srcHeight);
	      Graphics g = tmp.getGraphics();
	      int ratio = (srcWidth << 16) / width;
	      int pos = ratio/2;

	      //Horizontal Resize        

	      for (int x = 0; x < width; x++) {
	          g.setClip(x, 0, 1, srcHeight);
	          g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP);
	          pos += ratio;
	      }

	      Image resizedImage = Image.createImage(width, height);
	      g = resizedImage.getGraphics();
	      ratio = (srcHeight << 16) / height;
	      pos = ratio/2;        

	      //Vertical resize

	      for (int y = 0; y < height; y++) {
	          g.setClip(0, y, width, 1);
	          g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP);
	          pos += ratio;
	      }
	      return resizedImage;

	  }//resize image

}
